package com.raincat.toolsdemo.vaccin;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

import com.google.gson.Gson;
import com.ndktools.javamd5.core.MD5;
import com.raincat.tools.nettools.HttpsConfig;
import com.raincat.tools.nettools.NetCallBack;
import com.raincat.toolsdemo.R;
import com.raincat.toolsdemo.tools.BaseInfo;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * <pre>
 *     author : RainCat
 *     org    : Shenzhen JingYu Network Technology Co., Ltd.
 *     e-mail : nining377@gmail.com
 *     time   : 2020/08/16
 *     desc   : 预约
 *     version: 1.0
 * </pre>
 */
public class HospitalOrderActivity extends AppCompatActivity {
    private final String modeString = "%s模式启用中！";
    private final String dateString = "正在尝试获取预约日期，已重试%s次……";
    private final String timeString = "已获取到预约日期，尝试获取当前日期疫苗数量，已重试%s次……";
    private final String orderString = "预约中，已重试%s次……";

    private Context context;
    private TextView tv_info, tv_mode, tv_date, tv_time, tv_order, tv_order_status;

    private int hospitalId, productId;
    private Gson gson;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM", Locale.CHINA);
    private SharedPreferences preferences;
    private String token;

    //传参
    private String monthS, dateS;
    private HospitalOrderDateBean hospitalOrderDateBean;
    private HospitalOrderTimeBean hospitalOrderTimeBean;
    private boolean isDogMode = false, isStart = false;
    private int dateRetry = 0, timeRetry = 0, orderRetry = 0;
    //重试次数20次
    private int retryCount = 20;

    private String cname, birthday, tel, idcard;
    private int Ftime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hospitalorder_main);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        context = HospitalOrderActivity.this;
        gson = new Gson();
        preferences = PreferenceManager.getDefaultSharedPreferences(context);
        token = preferences.getString("token", "");

        init();
        loadData();
        listener();
    }

    private void loadData() {
        cname = preferences.getString("cname", "");
        birthday = preferences.getString("birthday", "");
        tel = preferences.getString("tel", "");
        idcard = preferences.getString("idcard", "");
        Ftime = preferences.getInt("Ftime", 1);

        if (cname.length() == 0) {
            Toast.makeText(context, "个人信息为空！", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            tv_info.setText("预约人信息：");
            tv_info.append("\n姓　名：" + cname);
            tv_info.append("\n身份证：" + idcard);
            tv_info.append("\n电　话：" + tel);
            tv_info.append("\n性　别：女");
            tv_info.append("\n生　日：" + birthday);
            tv_info.append("\n针　次：第" + Ftime + "针");
        }
    }

    private void init() {
        tv_info = findViewById(R.id.tv_info);
        tv_mode = findViewById(R.id.tv_mode);
        tv_date = findViewById(R.id.tv_date);
        tv_time = findViewById(R.id.tv_time);
        tv_order = findViewById(R.id.tv_order);
        tv_order_status = findViewById(R.id.tv_order_status);

        hospitalId = getIntent().getIntExtra("hospitalId", 0);
        productId = getIntent().getIntExtra("productId", 0);
        monthS = dateFormat.format(System.currentTimeMillis());
    }

    private void initText() {
        tv_mode.setText("已停止");
        tv_date.setText("");
        tv_time.setText("");
        tv_order.setText("");
        tv_order_status.setText("");
        monthS = "";
        dateS = "";
        dateRetry = 0;
        timeRetry = 0;
        orderRetry = 0;
        retryCount = 20;
    }

    private void listener() {
        findViewById(R.id.btn_dog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isStart)
                    return;
                isStart = true;
                isDogMode = true;
                tv_mode.setText(String.format(modeString, "疯狗"));
                getOrderDate();
            }
        });

        findViewById(R.id.btn_peace).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isStart)
                    return;
                isStart = true;
                isDogMode = false;
                tv_mode.setText(String.format(modeString, "和平"));
                getOrderDate();
            }
        });

        findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isStart = false;
            }
        });
    }

    /**
     * 获取预约日期
     */
    private void getOrderDate() {
        if (!isStart) {
            initText();
            return;
        }
        tv_date.setText(String.format(dateString, dateRetry));
        dateRetry++;
        HashMap<String, Object> header = new HashMap<>();
        header.put("Referer", BaseInfo.refererUrl);
        HashMap<String, Object> param = new HashMap<>();
        param.put("id", hospitalId);
        param.put("pid", productId);
        param.put("month", monthS);
        param.put("act", "GetCustSubscribeDateAll");
        new HttpsConfig().doGet(BaseInfo.otherUrl, param)
                .headers(header).start(context, new NetCallBack() {
            @Override
            public void result(String result) {
                hospitalOrderDateBean = gson.fromJson(result, HospitalOrderDateBean.class);
                if (hospitalOrderDateBean != null && hospitalOrderDateBean.getList() != null && hospitalOrderDateBean.getList().size() != 0) {
                    filterDate();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(500);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    getOrderDate();
                                }
                            });
                        }
                    }).start();
                }
            }

            @Override
            public void error(int errorCode, String error) {
                getOrderDate();
            }
        });
    }

    /**
     * 获取预约具体时间段
     */
    private void getOrderTime() {
        if (!isStart) {
            initText();
            return;
        }
        tv_time.setText(String.format(timeString, timeRetry));
        timeRetry++;
        HashMap<String, Object> header = new HashMap<>();
        header.put("Referer", BaseInfo.refererUrl);
        HashMap<String, Object> param = new HashMap<>();
        param.put("id", hospitalId);
        param.put("pid", productId);
        param.put("scdate", dateS);
        param.put("act", "GetCustSubscribeDateDetail");
        new HttpsConfig().doGet(BaseInfo.otherUrl, param)
                .headers(header).start(context, new NetCallBack() {
            @Override
            public void result(String result) {
                hospitalOrderTimeBean = gson.fromJson(result, HospitalOrderTimeBean.class);
                if (hospitalOrderTimeBean != null && hospitalOrderTimeBean.getList() != null && hospitalOrderTimeBean.getList().size() != 0) {
                    filterTime();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(500);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    getOrderTime();
                                }
                            });
                        }
                    }).start();
                }
            }

            @Override
            public void error(int errorCode, String error) {
                getOrderTime();
            }
        });
    }

    /**
     * 开始预约
     */
    private void order(final int mxid, final String md5) {
        if (!isStart) {
            initText();
            return;
        }
//        if (mxid == 0) {
//            Toast.makeText(context, "mxid错误，已结束！", Toast.LENGTH_SHORT).show();
//            initText();
//            return;
//        }
        tv_order.setText(String.format(orderString, orderRetry));
        orderRetry++;
        HashMap<String, Object> header = new HashMap<>();
        header.put("zftsl", md5);
        header.put("Referer", BaseInfo.refererUrl);
        header.put("Cookie", "ASP.NET_SessionId=" + token);
        HashMap<String, Object> param = new HashMap<>();
        param.put("act", "Save20");
        param.put("sex", 2);
        param.put("birthday", birthday);
        param.put("tel", tel);
        param.put("cname", cname);
        param.put("idcard", idcard);
        param.put("mxid", mxid);
        param.put("pid", productId);
        param.put("date", dateS);
        param.put("Ftime", Ftime);
        new HttpsConfig().doGet(BaseInfo.otherUrl, param)
                .headers(header).start(context, new NetCallBack() {
            @Override
            public void result(String result) {
                if (result.contains("提交成功")) {
                    Toast.makeText(context, "提交成功，检查状态中", Toast.LENGTH_SHORT).show();
                    getOrderStatus(mxid, md5);
                } else {
                    if (retryCount != 0) {
                        retryCount--;
                        order(mxid, md5);
                    } else {
                        Toast.makeText(context, "提交失败，重试中……", Toast.LENGTH_SHORT).show();
                        int index = -1;
                        for (int i = 0; i < hospitalOrderTimeBean.getList().size(); i++) {
                            if (hospitalOrderTimeBean.getList().get(i).getMxid() == mxid) {
                                index = i;
                                break;
                            }
                        }
                        List<HospitalOrderTimeBean.ListBean> listBean = hospitalOrderTimeBean.getList();
                        listBean.remove(index);
                        hospitalOrderTimeBean.setList(listBean);
                        filterTime();
                    }
                }
            }

            @Override
            public void error(int errorCode, String error) {
                order(mxid, md5);
            }
        });
    }

    /**
     * 获取预约状态
     */
    private void getOrderStatus(final int mxid, String md5) {
        if (!isStart) {
            initText();
            return;
        }
        tv_order.setText(String.format(orderString, orderRetry));
        HashMap<String, Object> header = new HashMap<>();
        header.put("zftsl", md5);
        header.put("Referer", BaseInfo.refererUrl);
        header.put("Cookie", "ASP.NET_SessionId=" + token);
        new HttpsConfig().doGet(BaseInfo.getOrderStatus)
                .headers(header).start(context, new NetCallBack() {
            @Override
            public void result(String result) {
                tv_order_status.setText(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.isNull("status") || jsonObject.getInt("status") != 200) {
                        Toast.makeText(context, "提交失败，重试中……", Toast.LENGTH_SHORT).show();
                        order(mxid, getMD5());
                    } else {
                        Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(int errorCode, String error) {
                order(mxid, getMD5());
            }
        });
    }

    private void filterDate() {
        if (isDogMode) {
            if (hospitalOrderDateBean.getList().size() > 2) {
                if (hospitalOrderDateBean.getList().get(1).isEnable())
                    dateS = hospitalOrderDateBean.getList().get(1).getDate();
                else
                    dateS = hospitalOrderDateBean.getList().get(0).getDate();
            } else {
                for (HospitalOrderDateBean.ListBean listBean : hospitalOrderDateBean.getList()) {
                    if (listBean.isEnable()) {
                        dateS = listBean.getDate();
                        break;
                    }
                }
            }
            getOrderTime();
        } else {
            String[] stringList = new String[hospitalOrderDateBean.getList().size()];
            for (int i = 0; i < hospitalOrderDateBean.getList().size(); i++) {
                if (hospitalOrderDateBean.getList().get(i).isEnable()) {
                    stringList[i] = hospitalOrderDateBean.getList().get(i).getDate();
                } else {
                    stringList[i] = hospitalOrderDateBean.getList().get(i).getDate() + "(满员)";
                }
            }

            AlertDialog alertDialog = new AlertDialog
                    .Builder(context)
                    .setTitle("选择预约日期")
                    .setItems(stringList, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dateS = hospitalOrderDateBean.getList().get(which).getDate();
                            getOrderTime();
                        }
                    }).create();
            alertDialog.show();
        }
    }

    private void filterTime() {
        int maxCount = 0, mxid = 0;
        if (isDogMode) {
            for (HospitalOrderTimeBean.ListBean listBean : hospitalOrderTimeBean.getList()) {
                if (listBean.getQty() > maxCount) {
                    mxid = listBean.getMxid();
                    maxCount = listBean.getQty();
                }
            }
            order(mxid, getMD5());
        } else {
            String[] stringList = new String[hospitalOrderTimeBean.getList().size()];
            for (int i = 0; i < hospitalOrderTimeBean.getList().size(); i++) {
                stringList[i] = hospitalOrderTimeBean.getList().get(i).getStartTime() + "-" + hospitalOrderTimeBean.getList().get(i).getEndTime()
                        + "(剩余：" + hospitalOrderTimeBean.getList().get(i).getQty() + "个）";
            }

            AlertDialog alertDialog = new AlertDialog
                    .Builder(context)
                    .setTitle("选择预约时间")
                    .setItems(stringList, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            int mxid = hospitalOrderTimeBean.getList().get(which).getMxid();
                            order(mxid, getMD5());
                        }
                    }).create();
            alertDialog.show();
        }
    }

    private String getMD5() {
        MD5 md5 = new MD5();
        return md5.getMD5ofStr("zfsw_" + System.currentTimeMillis() / 1000).toLowerCase();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
